from flask import Blueprint, redirect, url_for, flash, render_template
from flask_login import login_user, current_user, logout_user, login_required
from app.models import User, Crawler, Record, Subscribe
from app.forms import LoginForm, ChangePassword, RegisterForm
from app.extensions import db
from app.utils import redirect_back

user_bp = Blueprint('user', __name__)


@user_bp.route('/subscribe')
@login_required
def sub_manage():
    return render_template('index/subscribe.html')


@user_bp.route('/subscribe/<crawler_id>')
@login_required
def sub_add(crawler_id):
    this_cra = Crawler.query.get_or_404(crawler_id)
    if current_user.is_subscribing(this_cra):
        return redirect_back()
    current_user.subscribe(this_cra)
    return redirect(url_for('poly.detail', crawler_id=crawler_id))


@user_bp.route('/unsubscribe/<crawler_id>', methods=['POST'])
@login_required
def sub_delete(crawler_id):
    this_cra = Crawler.query.get_or_404(crawler_id)
    if not current_user.is_subscribing(this_cra):
        return redirect_back()
    current_user.unsubscribe(this_cra)
    return redirect(url_for('poly.detail', crawler_id=crawler_id))
